import { ACCESS_TOKEN_KEY, ACCESS_TOKEN_EXPIRE_KEY } from "../constants/key"

// 存储 token
export const setToken = (token) => {
  uni.setStorageSync(ACCESS_TOKEN_KEY, token)
  // 可以同时存储过期时间
  uni.setStorageSync(ACCESS_TOKEN_EXPIRE_KEY, Date.now() + 7 * 24 * 60 * 60 * 1000) // 7天
}

// 获取 token
export const getToken = () => {
  return uni.getStorageSync(ACCESS_TOKEN_KEY)
}

// 删除 token
export const removeToken = () => {
  uni.removeStorageSync(ACCESS_TOKEN_KEY)
  uni.removeStorageSync(ACCESS_TOKEN_EXPIRE_KEY)
}

// 检查 token 是否有效
export const isTokenValid = () => {
  const token = getToken()
  const expire = uni.getStorageSync(ACCESS_TOKEN_EXPIRE_KEY)

  if (!token) return false
  if (expire.data && Date.now() > expire.data) {
    removeToken()
    return false
  }
  return true
}